﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vibz.Common;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Vibz.Common.Model;

namespace Vibz.Common
{
    public class XmlModelSource : IModelSource
    {
        public ModelInformationList Models { get; set; }
        public ModelInformation GetModelInformation(string name)
        {
            try
            {
                List<ModelInformation> lstFiltered = Models.Where(m => m.Name == name).ToList();
                if (lstFiltered.Count == 0)
                    throw new Exception("No Model found with name '" + name + "' in configuration xml.");
                else return lstFiltered[0];
            }
            catch (Exception exc)
            {
                throw new Exception("Model information could not be loaded from config. \r\n", exc);
            }
        }
        public IModelManager GetModelManager(string name)
        {
            try
            {
                ModelInformation mi = GetModelInformation(name);
                return mi.Load();
            }
            catch (Exception exc)
            {
                throw new Exception("Error occured while initializing model manager. \r\n", exc);
            }
        }
        public XmlModelSource(string path)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            ParseXml(doc.OuterXml);
        }
        void ParseXml(string xmlContent)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ModelInformationList));
            try
            {
                using (StringReader textReader = new StringReader(xmlContent))
                {
                    using (XmlReader xmlReader = XmlReader.Create(textReader))
                    {
                        Models = (ModelInformationList)serializer.Deserialize(xmlReader);
                    }
                }
            }
            catch (Exception exc)
            {
                throw new Exception("Invalid configuration xml. ", exc);
            }
        }
    }
}
